<template>
  <view class="nv-file-upload" :style="{overflow: !$slots.default ? 'auto':''}">
    <template v-if="!$slots.default">
      <ne-file-preview
          :file-type="item.type"
          v-for="(item,index) in tempFiles"
          :key="index"
          :path="item.url"
          :file-url="item.url"
          :file-name="item.name"
          @delFile="delFile(item,index)"
          @imagePreview="imagePreview(item,index)"
          :is-preview="isPreview"
          :size="size"
      />
      <ne-file-preview file-type="upload" @click="fileClick" v-if="!isPreview && tempFiles.length < maxFile" :size="size"/>
    </template>
    <view @click="uploadFile" v-else>
      <slot></slot>
    </view>
  </view>
</template>

<script>
import NeFilePreview from "./NeFilePreview.vue";
import {Dialog, Toast} from "vant"
export default {
  name: 'NeFileUpload',
  components:{NeFilePreview},
  data() {
    return {
      tempFiles: [],
      storageSize: 5,
    }
  },
  props: {
    isPreview: {
      type: Boolean,
      default: false
    },
    previewFileList: {
      type: Array,
      default: () => []
    },
    value: {
      type: Array,
      default: () => []
    },
    maxFile: {
      type: [String, Number],
      default: 50
    },
    size: {
      type: String,
      default: 'default'
    },
    disabled: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    previewFileList(n) {
      if (n && n.length !== 0) {
        this.tempFiles = this.getFileMap(n)
      }
    },
    value(n) {
      if (n && n.length !== 0) {
        this.tempFiles = n
      }else{
        this.tempFiles = []
      }
    }
  },
  methods: {
    fileClick() {
      this.uploadFile()
    },
    /**
     * 上传文件
     **/
    uploadFile() {
      const _this = this
      if (!_this.disabled) {
        let fileFormatList = ['png', 'jpg','jpeg']
        uni.chooseFile({
          count: 1,
          extension: fileFormatList,
          success: (chooseImageRes) => {
            const fileData = chooseImageRes.tempFiles[0]
            const fileType = fileData.name.split('.').pop()
            // 校检文件大小
            const isLt = fileData.size / 1024 / 1024 < this.storageSize;
            if (!isLt) {
              Dialog.alert({
                message: `上传文件大小不能超过 ${this.storageSize} MB!`,
              }).then(() => { })
              return;
            }
            if (!fileFormatList.includes(fileType)) {
              Dialog.alert({
                message: `不能上传${fileType}类型的文件!`,
              }).then(() => {
              })
              return;
            }
            _this.tempFiles = _this.tempFiles.concat(chooseImageRes.tempFiles)
            const tempFilePaths = chooseImageRes.tempFilePaths;
            Toast.loading({
              message: '正在上传...',
              forbidClick: true,
            });
            uni.uploadFile({
              url: `/zgrsqfw-web/upload`,
              filePath: tempFilePaths[0],
              name: 'file',
              header: {},
              formData: {},
              success: (uploadFileRes) => {
                Toast.clear();
                _this.tempFiles.forEach(i => {
                  if (tempFilePaths[0] === i.path) {
                    i.url = JSON.parse(uploadFileRes.data).data.url
                  }
                })
                _this.tempFiles = [..._this.tempFiles]
                _this.$emit('input', _this.tempFiles)
                _this.$emit('change', _this.tempFiles)
              }
            });
          }
        })
      }
    },
    /**
     * 删除文件
     **/
    delFile(item, index) {
      const _this = this
      Dialog.confirm({
        title: '提示',
        message: '是否确认删除？',
      }).then(() => {
        _this.tempFiles.splice(index, 1)
        _this.$emit('input', _this.tempFiles)
        _this.$emit('change', _this.tempFiles)
      }).catch(() => {
      });
    },
    /**
     * 图片预览
     **/
    imagePreview(item, index) {
      uni.previewImage({
        indicator: 'number',
        current: index,
        urls: this.tempFiles.map(item => this.$getFilePath(item.url))
      })
    },
    getFileMap(list) {
      return list.map(item => ({
        path: item.filePath || item.fileUrl,
        name: this.getFileName(item),
        url: item.filePath || item.fileUrl,
        type: item.fileType,
        ...item
      }))
    },
    getFileName(item) {
      if (item.fileName) {
        return item.fileName
      } else if (item.filePath && (item.filePath.startsWith("http") || item.filePath.startsWith("https"))) {
        return item.filePath.split('/').pop()
      } else if (item.fileUrl && (item.fileUrl.startsWith("http") || item.fileUrl.startsWith("https"))) {
        return item.fileUrl.split('/').pop()
      }
      return item.filePath || item.fileUrl
    },
  },
  mounted() {
    if (this.previewFileList && this.previewFileList.length !== 0) {
      this.tempFiles = this.getFileMap(this.previewFileList)
    }
    if (this.value && this.value.length !== 0) {
      this.tempFiles = this.value
    }
  }
}
</script>
<style lang="less" scoped>
.nv-file-upload {
  display: flex;
  align-items: center;

  .nv-file-list {
    display: flex;
  }

  .nv-file-upload_but {
    width: 90px;
    height: 90px;
    border-radius: 10px;
    background: #F5F5F5;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      width: 24px;
      height: 24px;
    }
  }
}
</style>
